var mongoose = require("./index");

// PC端用户登录模型
let pcuserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3,
    maxlength: 20,
  },
  password: {
    type: String,
    required: true,
    minlength: 6,
  },
});

// 权限模型
let permissionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    code: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    description: {
      type: String,
      default: "",
    },
    module: {
      type: String,
      required: true,
      trim: true,
    },
    type: {
      type: String,
      enum: ["menu", "button", "api"],
      default: "menu",
    },
    status: {
      type: Boolean,
      default: true,
    },
  },
  {
    timestamps: true,
  }
);

// 角色模型
let roleSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    code: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    description: {
      type: String,
      default: "",
    },
    permissions: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Permission",
      },
    ],
    status: {
      type: Boolean,
      default: true,
    },
  },
  {
    timestamps: true,
  }
);

// 用户角色关联模型
let userRoleSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Pcusers",
      required: true,
    },
    roleId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Role",
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

// 小程序登录模型
let wechatUserSchema = new mongoose.Schema({
  openid: {
    type: String,
    required: function () {
      // 如果没有手机号，则openid必填
      return !this.phone;
    },
    unique: true,
    trim: true,
    sparse: true, // 允许为空，但如果存在必须唯一
  },
  unionid: {
    type: String,
    trim: true,
  },
  session_key: {
    type: String,
    required: function () {
      // 如果有真实的微信openid，则session_key必填
      // 排除手机号登录的伪openid（以phone_开头）
      return !!this.openid && !String(this.openid).startsWith("phone_");
    },
  },
  nickname: {
    type: String,
    default: "",
  },
  avatarUrl: {
    type: String,
    default: "",
  },
  // 手机号相关字段
  phone: {
    type: String,
    unique: true,
    sparse: true, // 允许为空，但如果存在必须唯一
    trim: true,
    validate: {
      validator: function (phone) {
        // 如果手机号存在，验证格式
        return !phone || /^1[3-9]\d{9}$/.test(phone);
      },
      message: "手机号格式不正确",
    },
  },
  phoneVerified: {
    type: Boolean,
    default: false,
  },
  // 登录类型：wechat(微信登录)、phone(手机号登录)、both(两种都有)
  loginType: {
    type: String,
    enum: ["wechat", "phone", "both"],
    default: function () {
      if (this.openid && this.phone) return "both";
      if (this.phone) return "phone";
      return "wechat";
    },
  },
  agreeProtocol: {
    type: Boolean,
    default: false,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  lastLoginAt: {
    type: Date,
    default: Date.now,
  },
  // 最后一次手机号登录时间
  lastPhoneLoginAt: {
    type: Date,
  },
  // 最后一次微信登录时间
  lastWechatLoginAt: {
    type: Date,
  },
  status: {
    type: Boolean,
    default: true,
  },
});

// 添加索引以优化查询性能
userRoleSchema.index({ userId: 1 }); // 按用户ID查询角色
userRoleSchema.index({ roleId: 1 }); // 按角色ID查询用户
userRoleSchema.index({ userId: 1, roleId: 1 }, { unique: true }); // 复合索引，确保用户-角色对唯一

// 为微信用户表添加索引
wechatUserSchema.index({ openid: 1 }); // 微信openid索引
wechatUserSchema.index({ phone: 1 }); // 手机号索引
wechatUserSchema.index({ loginType: 1 }); // 登录类型索引
wechatUserSchema.index({ phoneVerified: 1 }); // 手机号验证状态索引
wechatUserSchema.index({ status: 1 }); // 用户状态索引
wechatUserSchema.index({ createdAt: -1 }); // 创建时间索引（降序）
wechatUserSchema.index({ lastLoginAt: -1 }); // 最后登录时间索引（降序）

// 添加预处理中间件
wechatUserSchema.pre("save", function (next) {
  // 自动设置登录类型
  if (this.openid && this.phone) {
    this.loginType = "both";
  } else if (this.phone) {
    this.loginType = "phone";
  } else if (this.openid) {
    this.loginType = "wechat";
  }

  // 更新最后登录时间
  this.lastLoginAt = new Date();

  next();
});

// 添加实例方法
wechatUserSchema.methods.updatePhoneLogin = function () {
  this.lastPhoneLoginAt = new Date();
  this.lastLoginAt = new Date();
  return this.save();
};

wechatUserSchema.methods.updateWechatLogin = function () {
  this.lastWechatLoginAt = new Date();
  this.lastLoginAt = new Date();
  return this.save();
};

// 添加静态方法
wechatUserSchema.statics.findByPhone = function (phone) {
  return this.findOne({ phone: phone, status: true });
};

wechatUserSchema.statics.findByOpenid = function (openid) {
  return this.findOne({ openid: openid, status: true });
};

// 创建模型
let pcusermodel = mongoose.model("Pcusers", pcuserSchema, "Pcusers");
let permissionModel = mongoose.model(
  "Permission",
  permissionSchema,
  "permissions"
);
let roleModel = mongoose.model("Role", roleSchema, "roles");
let userRoleModel = mongoose.model("UserRole", userRoleSchema, "user_roles");
let usermodel = mongoose.model("WechatUser", wechatUserSchema, "wechat_users");

// 导出所有模型
module.exports = {
  pcusermodel,
  permissionModel,
  roleModel,
  userRoleModel,
  usermodel,
};
